package com.trkj.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.jpa.IYzrMedInstockDAO;
import com.trkj.dao.jpa.IYzrMedInstockDetDAO;
import com.trkj.dao.jpa.IYzrMedStockDAO;
import com.trkj.dao.jpa.IYzrMedicineDAO;
import com.trkj.dao.jpa.IYzrPurchOrderDAO;
import com.trkj.dao.jpa.IYzrPurchOrderDetDAO;
import com.trkj.dao.jpa.IYzrStoreCountDAO;
import com.trkj.dao.jpa.IYzrStoreCountDetDAO;
import com.trkj.dao.jpa.IYzrStorehouseDAO;
import com.trkj.dao.jpa.IYzrTbstaffDAO;
import com.trkj.pojos.Tbstaff;
import com.trkj.pojos.YzrMedInstock;
import com.trkj.pojos.YzrMedInstockDet;
import com.trkj.pojos.YzrMedStock;
import com.trkj.pojos.YzrMedicine;
import com.trkj.pojos.YzrPurchOrder;
import com.trkj.pojos.YzrPurchOrderDet;
import com.trkj.pojos.YzrStoreCount;
import com.trkj.pojos.YzrStoreCountDet;
import com.trkj.pojos.YzrStorehouse;
import com.trkj.vo.YzrInstockVo;
import com.trkj.vo.YzrMedInstockVo;
import com.trkj.vo.YzrMedStockVo;
import com.trkj.vo.YzrStoreCountDetVo;
import com.trkj.vo.YzrStoreCountVo;

@Service
@Transactional
public class YzrInstockService {
	
	@Autowired
	private IYzrMedStockDAO yzrMedStockDAO;//库存
	@Autowired
	private IYzrMedInstockDAO yzrMedInstockDAO;//入库
	@Autowired
	private IYzrMedInstockDetDAO yzrMedInstockDetDAO;//入库详情
	@Autowired
	private IYzrPurchOrderDAO yzrPurchOrderDAO;//采购单
	@Autowired
	private IYzrPurchOrderDetDAO yzrPurchOrderDetDAO;//采购明细单
	@Autowired
	private IYzrMedicineDAO yzrMedicineDAO;//药品
	@Autowired
	private IYzrStorehouseDAO yzrStorehouseDAO;//仓库	
	@Autowired
	private IYzrStoreCountDAO yzrStoreCountDAO;//盘点
	@Autowired
	private IYzrStoreCountDetDAO yzrStoreCountDetDAO;//盘点详情
	@Autowired
	private IYzrTbstaffDAO yzrTbstaffDAO;
	
	/**
	 * 根据id查找盘点明细信息
	 * @param countId
	 * @return
	 */
	public List<YzrStoreCountDet> queryCountDetByCountId(String countId){
		return yzrStoreCountDetDAO.findBycountId(countId);
	}
	
	
	
	/**
	 * 根据id查找盘点信息
	 * @param countId
	 * @return
	 */
	public YzrStoreCountVo queryCountById(String countId){
		YzrStoreCount count = yzrStoreCountDAO.findOne(countId);
		return countPoToVo(count);
	}
	
	
	
	
	/**
	 * 分页查询盘点信息
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String,Object> queryAllCount(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrStoreCount> list = yzrStoreCountDAO.findAllCount(pr);
		System.err.println("长度："+list.size());
		long total = yzrStoreCountDAO.count();
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", countListToVo(list));
		return map;
	}
	private List<YzrStoreCountVo> countListToVo(List<YzrStoreCount> list){
		if(list == null) return null;
		List<YzrStoreCountVo> listVo = new ArrayList<>();
		
		for(YzrStoreCount purchOrder: list){
			YzrStoreCountVo purchOrderVo = countPoToVo(purchOrder);
			listVo.add(purchOrderVo);
		}
		return listVo;
	}
	public YzrStoreCountVo countPoToVo(YzrStoreCount purchOrder){
		YzrStoreCountVo purchOrderVo = new YzrStoreCountVo();
		purchOrderVo.setStoreCountId(purchOrder.getStoreCountId());
		purchOrderVo.setStoreCountPerson(purchOrder.getStoreCountPerson());
		purchOrderVo.setStoreCountDate(purchOrder.getStoreCountDate());
		purchOrderVo.setStoreCountStoreId(purchOrder.getStoreCountStoreId());


		
		BigDecimal rkr = purchOrder.getStoreCountPerson();
		String store = purchOrder.getStoreCountStoreId();
		
		if(rkr != null){
			Tbstaff staff = yzrTbstaffDAO.findOne(rkr.longValue());
			purchOrderVo.setStaffName(staff!=null? staff.getStaffName():null);
		}
		if(store != null){		
			YzrStorehouse storehouse = yzrStorehouseDAO.findOne(store);	
			purchOrderVo.setStoreName(storehouse != null ? storehouse.getStoreName() : null);
		}		

		return purchOrderVo;
	}
	
	
	
	/**
	 * 根据选中，查看入库详情药品
	 */
	public List<YzrMedInstockDet> queryInstockDetById(String intockId){
		List<YzrMedInstockDet> list = yzrMedInstockDetDAO.findInstockDetById(intockId);
		return list;
	}
	
	
	
	/**
	 * 根据选中，查看入库信息
	 *  
	 */
	public YzrMedInstockVo queryInstockById(String intockId){
		YzrMedInstock instock = yzrMedInstockDAO.findOne(intockId);
		return instockPoToVo(instock);
	}
	
	
	/**
	 * 分页查询入库信息
	 */
	public Map<String,Object> queryAllInstock(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedInstock> list = yzrMedInstockDAO.findAllInstock(pr);
		System.err.println("长度："+list.size());
		long total = yzrMedInstockDAO.count();
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", instockListToVo(list));
		return map;
	}
	private List<YzrMedInstockVo> instockListToVo(List<YzrMedInstock> list){
		if(list == null) return null;
		List<YzrMedInstockVo> listVo = new ArrayList<>();
		
		for(YzrMedInstock purchOrder: list){
			YzrMedInstockVo purchOrderVo = instockPoToVo(purchOrder);
			listVo.add(purchOrderVo);
		}
		return listVo;
	}
	public YzrMedInstockVo instockPoToVo(YzrMedInstock purchOrder){
		YzrMedInstockVo purchOrderVo = new YzrMedInstockVo();
		purchOrderVo.setMedInstockId(purchOrder.getMedInstockId());
		purchOrderVo.setMedInstockKind(purchOrder.getMedInstockKind());
		purchOrderVo.setMedInstockPurchOrderId(purchOrder.getMedInstockPurchOrderId());
		purchOrderVo.setMedInstockStoreName(purchOrder.getMedInstockStoreName());
		purchOrderVo.setMedInstockTime(purchOrder.getMedInstockTime());
		purchOrderVo.setMedInstockBrokerage(purchOrder.getMedInstockBrokerage());//入库人

		
		BigDecimal rkr = purchOrder.getMedInstockBrokerage();
		String store = purchOrder.getMedInstockStoreName();
		
		if(rkr != null){
			Tbstaff staff = yzrTbstaffDAO.findOne(rkr.longValue());
			purchOrderVo.setStaffName(staff!=null? staff.getStaffName():null);
		}
		if(store != null){		
			YzrStorehouse storehouse = yzrStorehouseDAO.findOne(store);	
			purchOrderVo.setStoreName(storehouse != null ? storehouse.getStoreName() : null);
		}		

		return purchOrderVo;
	}
	
	
	
	
	
	
	
	/**
	 * 统计不同类型药品的入库数量
	 */
	public List<YzrInstockVo> rukuCount(){
		List<YzrMedInstockDet> list = (List<YzrMedInstockDet>) yzrMedInstockDetDAO.findAll();
		List<YzrInstockVo> countList = new ArrayList<>();
		BigDecimal zhongya = new BigDecimal("0");
		BigDecimal xiyao = new BigDecimal("0");
		BigDecimal zhusheji = new BigDecimal("0");
		BigDecimal waiyongyao = new BigDecimal("0");
		
		//统计的是不同类型的药品的数量有多少
		for(YzrMedInstockDet det: list){
			YzrMedicine medicine = yzrMedicineDAO.findOne(det.getMedInstockDetMedId());
			
			if(medicine != null){
				if(medicine.getMedKind().equals("中药")){
					zhongya = zhongya.add(det.getMedInstockDetNumber());
				}else if(medicine.getMedKind().equals("西药")){
					xiyao = xiyao.add(det.getMedInstockDetNumber());
				}else if(medicine.getMedKind().equals("注射剂")){
					zhusheji = zhusheji.add(det.getMedInstockDetNumber());
				}else{
					waiyongyao = waiyongyao.add(det.getMedInstockDetNumber());
				}
			}
		}
		int a = zhongya.intValue();
		int b = xiyao.intValue();
		int c = zhusheji.intValue();
		int d = waiyongyao.intValue();

		YzrInstockVo count1 = new YzrInstockVo();
		count1.setName("中药");
		count1.setValue(a);
		countList.add(count1);
		
		YzrInstockVo count2 = new YzrInstockVo();
		count2.setName("西药");
		count2.setValue(b);
		countList.add(count2);
		
		YzrInstockVo count3 = new YzrInstockVo();
		count3.setName("注射剂");
		count3.setValue(c);
		countList.add(count3);
		
		YzrInstockVo count4 = new YzrInstockVo();
		count4.setName("外用药");
		count4.setValue(d);
		countList.add(count4);
		
		return countList;
	}
	
	
	
	
	/**
	 * 添加盘点数据到数据库
	 * @param storeVo
	 * @param pdrck
	 * @param pdr
	 */
	public void addPandian(YzrStoreCountDetVo storeVo, String pdrck, String pdr){
		/*盘点编号，盘点日期，盘点人，仓库
		盘点详情编号，盘点编号，药品编号，药品名称，批号，单位，出库数量，入库数量，库存数量，结存数量，盈亏数量，销售数量，盘点结果*/
		//1.生成编号，添加盘点表
		String year = getNowDate();
		//拼接
		String name = "PD-" + year;	//盘点s
		String nameDet = "PX-" + year;//盘点详情

		String n = yzrStoreCountDAO.findMaxId(name);
		
	
		//生成id
		YzrEntityService entityService = new YzrEntityService();
		String pandianId = entityService.getId(name, n);
		
		YzrStoreCount pandian = new YzrStoreCount();
		pandian.setStoreCountId(pandianId);
		pandian.setStoreCountPerson(new BigDecimal(pdr));
		pandian.setStoreCountStoreId(pdrck);
		pandian.setStoreCountDate(new Date());
		yzrStoreCountDAO.save(pandian);
		
		//2.生成盘点详情表编号，添加数据
		List<YzrStoreCountDet> listDet = storeVo.getStoreList();
		for(YzrStoreCountDet storeDet: listDet){
			
			YzrStoreCountDet pandianDet  = new YzrStoreCountDet();
			
			String nDet = yzrStoreCountDetDAO.findMaxId(nameDet);
			
			pandianDet.setStoreCountDetId(entityService.getId(nameDet, nDet));//详情编号
			pandianDet.setCountDetCountId(pandianId);//盘点编号
			pandianDet.setStoreCountDetMedId(storeDet.getStoreCountDetMedId());//药品id
			pandianDet.setStoreCountDetMedName(storeDet.getStoreCountDetMedName());//药品名
			pandianDet.setStoreCountDetBatchnumber(storeDet.getStoreCountDetBatchnumber());//批号
			pandianDet.setStoreCountDetMedUnit(storeDet.getStoreCountDetMedUnit());//单位
			pandianDet.setStoreCountDetStockNumber(storeDet.getStoreCountDetStockNumber());//库存数量
			pandianDet.setStoreCountDetInputNum(storeDet.getStoreCountDetInputNum());//盘点数量
			pandianDet.setStoreCountDetYkNum(storeDet.getStoreCountDetYkNum());//盈亏数量
			yzrStoreCountDetDAO.save(pandianDet);
		}
		

	}
	
	
	
	/**
	 * 根据仓库id查询
	 * @param page
	 * @param rows
	 * @param medName
	 * @return
	 */
	public Map<String,Object> queryMedByStore(int page, int rows, String cangku){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedStock> list = yzrMedStockDAO.findByStore(cangku, pr);
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", storeListToVo(list));
		return map;
	}
	/**
	 * 根据药品名模糊查询
	 * @param page
	 * @param rows
	 * @param medName
	 * @return
	 */
	public Map<String,Object> queryMedByName(int page, int rows, String medName, String cangku){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedStock> list = yzrMedStockDAO.findByMedName(medName,cangku, pr);
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", storeListToVo(list));
		return map;
	}
	
	/**
	 * 分组查询药库库存
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String,Object> queryMedStoreGroup(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedStock> list = yzrMedStockDAO.findByGroup(pr);
		long total = yzrMedStockDAO.count();
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", storeListToVo(list));
		return map;
	}
	private List<YzrMedStockVo> storeListToVo(List<YzrMedStock> list){
		if(list == null) return null;
		List<YzrMedStockVo> listVo = new ArrayList<>();
		
		for(YzrMedStock purchOrder: list){
			YzrMedStockVo purchOrderVo = storePoToVo(purchOrder);
			listVo.add(purchOrderVo);
		}
		return listVo;
	}
	public YzrMedStockVo storePoToVo(YzrMedStock purchOrder){
		YzrMedStockVo purchOrderVo = new YzrMedStockVo();
		purchOrderVo.setMedStockId(purchOrder.getMedStockId());
		purchOrderVo.setMedStockStoreId(purchOrder.getMedStockStoreId());
		purchOrderVo.setMedStockMedId(purchOrder.getMedStockMedId());
		purchOrderVo.setMedStockMedName(purchOrder.getMedStockMedName());
		purchOrderVo.setMedStockBatchnumber(purchOrder.getMedStockBatchnumber());
		purchOrderVo.setMedStockMedKind(purchOrder.getMedStockMedKind());
		purchOrderVo.setMedStockGuige(purchOrder.getMedStockGuige());
		purchOrderVo.setMedStockUnit(purchOrder.getMedStockUnit());
		purchOrderVo.setMedStockNumber(purchOrder.getMedStockNumber());
		purchOrderVo.setMedStockPrice(purchOrder.getMedStockPrice());
		purchOrderVo.setMedStockMoney(purchOrder.getMedStockMoney());
		
		String zdr = purchOrder.getMedStockStoreId();
		
		if(zdr != null){		
			YzrStorehouse storehouse = yzrStorehouseDAO.findOne(zdr);	
			purchOrderVo.setStoreName(storehouse != null ? storehouse.getStoreName() : null);
		}		
		
		return purchOrderVo;
	}
	
	
	
	
	
	/**
	 * 入库
	 * @param list
	 * @param orderId
	 * @param kind
	 * @param store
	 * @param staffId
	 * @param checkDate
	 */
	public void submitInstockMed(String[] list, String orderId, String kind,
			String store,String staffId, Date checkDate){
		//入库编号，入库类型（采购入库，调拨入库），入库人，仓库编号，入库的时间，采购订单号（已验收，验收通过,判断数量是否入库）
		//入库详情编号，入库编号，药品编号，药品名称，批号，规格，单价，数量，金额，生产日期，保质期

		//1.生成入库单号和入库详情单号；将信息添入
		// 获取年份
		String year = getNowDate();
		//拼接
		String name = "RK-" + year;	
		String nameDet = "RD-" + year;
		String nameStore = "KC-" + year;	
		String n = yzrMedInstockDAO.findMaxId(name);
		
	
		//生成id
		YzrEntityService entityService = new YzrEntityService();
		String inStockId = entityService.getId(name, n);
		
		
		//添加入库单
		YzrMedInstock inStock = new YzrMedInstock();
		inStock.setMedInstockId(inStockId);//入库编号
		inStock.setMedInstockKind(kind);//入库类型
		inStock.setMedInstockBrokerage(new BigDecimal(staffId));//入库人
		inStock.setMedInstockStoreName(store);//仓库编号
		inStock.setMedInstockTime(new Date());//入库的时间
		inStock.setMedInstockPurchOrderId(orderId);//采购订单号
		yzrMedInstockDAO.save(inStock);
		
		//添加入库详情单
		//List<YzrPurchOrderDet> orderList = new ArrayList<YzrPurchOrderDet>();
		
		for(String id : list){
			//orderList.add(yzrPurchOrderDetDAO.findOne(id));
			
			YzrPurchOrderDet orderDet = yzrPurchOrderDetDAO.findOne(id);
			
			if(orderDet.getOrderDetNumber() != new BigDecimal("0")){
				
				//添加入库详情单
				YzrMedInstockDet inStockDet = new YzrMedInstockDet();			
				String nDet = yzrMedInstockDetDAO.findMaxId(nameDet);
				inStockDet.setMedInstockDetId(entityService.getId(nameDet, nDet));//入库详情编号
				inStockDet.setMedRukuId(inStockId);//入库编号
				inStockDet.setMedInstockDetMedId(orderDet.getOrderDetMedId());//药品编号
				inStockDet.setMedInstockDetMedName(orderDet.getOrderDetMedName());//药品名称
				inStockDet.setMedInstockDetBatchnumber(orderDet.getOrderDetBatchnumber());//批号
				inStockDet.setMedInstockDeGuige(orderDet.getOrderDetGuige());//规格
				inStockDet.setMedInstockDetPrice(orderDet.getOrderDetPrice());//单价
				inStockDet.setMedInstockDetNumber(orderDet.getOrderDetNumber());//数量
				inStockDet.setMedInstockDetMoney(orderDet.getOrderDetMoney());//金额
				yzrMedInstockDetDAO.save(inStockDet);
				
				
				
				
				//2.将明细添加到库存中（问题：如何判断同样的药品）			
				String medId = orderDet.getOrderDetMedId();
				String batchNumber = orderDet.getOrderDetBatchnumber();
				YzrMedStock yzrmedStock = yzrMedStockDAO.findByMedicine(medId, batchNumber);
				
				if(yzrmedStock == null){
					
					YzrMedStock medStock = new YzrMedStock();
					String storeId = yzrMedStockDAO.findMaxId(nameStore);
					medStock.setMedStockId(entityService.getId(nameStore, storeId));
					medStock.setMedStockStoreId(store);
					medStock.setMedStockMedId(orderDet.getOrderDetMedId());
					medStock.setMedStockMedName(orderDet.getOrderDetMedName());
					medStock.setMedStockBatchnumber(orderDet.getOrderDetBatchnumber());
					YzrMedicine med = yzrMedicineDAO.findOne(orderDet.getOrderDetMedId());
					medStock.setMedStockMedKind(med.getMedKind());
					medStock.setMedStockGuige(orderDet.getOrderDetGuige());
					medStock.setMedStockUnit(orderDet.getOrderDetMedUnit());
					medStock.setMedStockPrice(orderDet.getOrderDetPrice());
					medStock.setMedStockNumber(orderDet.getOrderDetNumber());
					medStock.setMedStockMoney(orderDet.getOrderDetMoney());
					yzrMedStockDAO.save(medStock);
				}else{
					yzrmedStock.setMedStockNumber(orderDet.getOrderDetNumber().add(yzrmedStock.getMedStockNumber()));
					yzrMedStockDAO.save(yzrmedStock);
				}
				
				
			}else{
				System.err.println(orderDet.getOrderDetMedName()+"已退货");
			}
			
		}	
		
		
		//3.根据‘orderId’找到采购订单，修改采购订单的入库状态
		YzrPurchOrder order =  yzrPurchOrderDAO.findOne(orderId);
		order.setPurchInstockState("已入库");
		yzrPurchOrderDAO.save(order);	
	}
	
	/**
	 * 格式化日期
	 * @return
	 */
	public static String getNowDate() {
		  Date currentTime = new Date();
		  SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		  String dateString = formatter.format(currentTime);
		  return dateString;
	}
}
